<template>
  <div>
    <el-upload
      style='position: relative;top: 10px;height: 160px; '
      :file-list='fileList'
      class="avatar-uploader"
      :limit='1'
      :action="uploadUrl"
      accept="image/jpeg,image/gif,image/png,image/bmp"
      list-type="picture-card"
      :data='uploadData'
      :on-success="handleAvatarSuccess"
      :on-error="uploadError"
      :before-upload="beforeAvatarUpload"
      :on-preview="doLookImg"
      :on-remove="doDeleteImg">
      <i class="el-icon-plus" ></i>
    </el-upload>

    <el-dialog :visible.sync="uploadDialogVisible" :append-to-body="true">
      <img width="800" :src="dialogImageUrl" alt=""
           style="display: block; max-width: 100%; margin: 0 auto"
      >
    </el-dialog>
  </div>
</template>


<script>

import {getUpToken} from "@/api/FileUploadApi";
const qiniu = require('qiniu-js')
export default {
  data() {
    return {
      uploadUrl: '',
      uploadData: {key:'',token:''},
      formAdd: { brandLogo: '' },
      mainInfo: {brandLogo: ''},
      domain:'http://cdn.xingjiyxy.top',
      fileList:[],
      uploadDialogVisible:false,
      uploadDialogImg:'',
      editState:false,
      imgUrl:'',
      imgWatermarkUrl:'',
      dialogImageUrl:'',
    }
  },
  mounted() {
    getUpToken({}).then((res)=> {
      if (res.code === 200) {
        this.uploadData.token = res.upToken
      }
      const config = {
        useCdnDomain: true,
        region: qiniu.region.z2
      };
      qiniu.getUploadUrl(config, this.uploadData.token).then(res => {
        console.log(res)
        this.uploadUrl = res;
      })
    })
  },
  methods: {
    doDeleteImg(file, fileList) {
      console.log('删除成功',file, fileList)
      // let logoAry;
      // let key;
      // if (this.editState) {
      //   logoAry = this.mainInfo.brandLogo.split('/');
      // } else {
      //   logoAry = this.formAdd.brandLogo.split('/');
      // }
      // key = logoAry[logoAry.length - 1];
      // deleteQiniuImg({key}).then(res=> {
      //   if (res.code === '0') {
      //     if (this.editState) {
      //       this.mainInfo.brandLogo = '';
      //     } else {
      //       this.formAdd.brandLogo = '';
      //     }
      //   } else {
      //     this.$message.error(res.msg)
      //   }
      // })
    },
    doLookImg() {
      this.uploadDialogVisible = true;
      this.uploadDialogImg = this.editState ? this.mainInfo.brandLogo : this.formAdd.brandLogo;
    },
    handleAvatarSuccess(res, file, fileList) {
      console.log('上传成功', res,file, fileList)

      const imgLink = qiniu.watermark({
        mode: 2,  // 文字水印
        text: '@诸暨相亲记', // 水印文字，mode = 2 时 **必需**
        dissolve: 50,          // 透明度，取值范围1-100，非必需，下同
        gravity: 'SouthWest',  // 水印位置，同上
        fontsize: 500,         // 字体大小，单位: 缇
        font: '黑体',           // 水印文字字体
        dx: 600,               // 横轴边距，单位:像素(px)
        dy: 10,               // 纵轴边距，单位:像素(px)
        fill: '#FFF000'        // 水印文字颜色，RGB格式，可以是颜色名称
      }, this.uploadData.key, this.domain)
      this.imgUrl = imgLink;
      this.dialogImageUrl = imgLink;
      this.imgWatermarkUrl = imgLink;

      // this.fileList.push({ name: res.fileName, url: this.imgUrl });
      // this.file =  this.imgUrl
      // this.$emit("input", this.listToString(this.fileList));
      this.$emit("input", this.imgUrl);

      if (this.editState) {
        this.mainInfo.brandLogo =this.imgUrl;
      } else {
        this.formAdd.brandLogo = this.imgUrl;
      }
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === "image/png";
      const isJPEG = file.type === "image/jpeg";
      const isJPG = file.type === "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPNG && !isJPEG && !isJPG) {
        this.$message.error("上传头像图片只能是 jpg、png、jpeg 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      this.uploadData.key = `xiangqin_pic_${new Date().getTime()}_${file.name}`;
    },
    uploadError(err, file, fileList) {
      this.$message({
        message: "上传出错，请重试！",
        type: "error",
        center: true
      });
    },

    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url.replace(this.baseUrl, "") + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },

  }
}
</script>
